package luj.tool.jnproxyan.proxy.network.socks.actor.root.message.http.proxy2s.request.write;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import luj.tool.jnproxyan.proxy.network.logger.Proxy2sLogger;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5Actor;
import luj.tool.jnproxyan.proxy.network.socks.request.SocksRequest;
import luj.tool.jnproxyan.proxy.network.socks.request.op.RequestByIdGetter;
import luj.tool.jnproxyan.proxy.stats.http.history.HistoryCurItemGetter;
import luj.tool.jnproxyan.proxy.stats.http.history.state.HttpHistoryItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
final class OnP2sReqWrite implements Socks5Actor.Handler<P2sReqWriteMsg> {

  @Override
  public void onHandle(Context ctx) throws Exception {
    Socks5Actor self = ctx.getActorState(this);
    P2sReqWriteMsg msg = ctx.getMessage(this);

    Long socksId = msg.socksId();
    SocksRequest socks = _reqGetter.inject(self, socksId).getReq();

    ByteBuf data = msg.data();
    int dataSize = data.readableBytes();
    new Proxy2sLogger(LOG, socksId).log("发送B给<站>，大小：{}", dataSize);

    Channel p2sConn = socks.getP2sConn3();
    p2sConn.writeAndFlush(data);

    // 更新历史统计
    HttpHistoryItem curItem = _curItemGetter.inject(self.getHttpHistoryDat(), socksId).getCurrent();
    curItem.setBytesProxy2s(curItem.getBytesProxy2s() + dataSize);
  }

  private static final Logger LOG = LoggerFactory.getLogger(OnP2sReqWrite.class);

  @Autowired
  RequestByIdGetter _reqGetter;

  @Autowired
  HistoryCurItemGetter _curItemGetter;
}
